const express =require('express')
const router =express.Router()
const {db,genid} =require("../db/DbUtils")

//添加接口
router.post("/add",async(req,res)=>{
    let {name }=req.body
    const insert_sql ="INSERT INTO `category` (`id`,`name`) VALUES (?,?)"
    let {err,rows}=await db.async.run(insert_sql[genid.NextId(),name])
    if(err==null){
        res.send({
            code:200,
            msg:"add成功"
        })
    }else{
        res.send({
            code:500,
            msg:"add失败"
        })
    }
})
//修改接口
router.put("/update",async(req,res)=>{
    let {id,name }=req.body
    const update_sql ="UPDATE `category` SET `name` =? WHERE `id`=?"
    
    let {err,rows}=await db.async.run(update_sql,[name,id])
    if(err==null){
        res.send({
            code:200,
            msg:"xiuegai 成功"
        })
    }else{
        res.send({
            code:500,
            msg:"xiugai失败"
        })
    }
})
//删除接口
router.delete("/delete",async(req,res)=>{
    let id=req.query.id
    const delete_sql ="DELETE FROM `category` WHERE `id`=?"
    let {err,rows}=await db.async.run(delete_sql,[id])
    if(err==null){
        res.send({
            code:200,
            msg:"del成功"
        })
    }else{
        res.send({
            code:500,
            msg:"del失败"
        })
    }
})


router.get("/list",async(req,res)=>{
    const search_sql = "SELECT * FROM `category`"

    let {err,rows} =await db.async.all(search_sql,[])
    if(err==null){
        res.send({
            code:200,
            msg:"search成功",
            rows
        })
    }else{
        res.send({
            code:500,
            msg:"search失败"
        })
    }
})
module.exports=router